package com.rtwo.trafficmanagement;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.SystemClock;
import android.provider.Settings;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.RotateAnimation;
import android.view.animation.ScaleAnimation;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.rtwo.trafficaction.TrafficHandle;

import java.text.DecimalFormat;

/**
 * ClassName: MainActivity
 * MethodName: 
 * Comment:
 * Author:Zhouhao
 * Created on 0:20 2015/8/22
 */
public class MainActivity extends Activity {

    private ImageButton start,stop,help;
    private RadioButton mobileTrafficData,allTrafficData;
    private RadioGroup trafficDataOption;
    private EditText limitedData;
    private TextView showData;
    private String trafficLimitedData;
    private TrafficHandle.TrafficBinder trafficBinder;
    private TrafficConnection monitor = new TrafficConnection();
    private boolean serviceFlag = false;
    private MyHandler displayTrafficData = new MyHandler();
    private static final int DISPLAYTRAFFICDATA = 1;
    private static final int DISPLAYDIALOG = 2;
    public static int option=1;
    private Thread displayDataThread;
    private boolean hasDialog = false;
    private LinearLayout mainPanle;

    class TrafficConnection implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            trafficBinder = (TrafficHandle.TrafficBinder)service;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            //pass
        }
    }

    class MyHandler extends Handler{
        @Override
        public void handleMessage(Message msg) {
            switch(msg.what){
                case DISPLAYTRAFFICDATA:
                    if(trafficBinder!=null){
                        DecimalFormat df=new java.text.DecimalFormat("#.##");
                        String trafficData = df.format(trafficBinder.getTrafficData());
                        showData.setText("" + trafficData + "MB");
                    }
                    break;
                case DISPLAYDIALOG:
                    AlertDialog.Builder setting = new AlertDialog.Builder(MainActivity.this);
                    setting.setTitle("网络数据监控");
                    setting.setMessage("流量使用已经超过了您设置的数值,是否关闭网络?");
                    setting.setPositiveButton("设置", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Intent intent = new Intent(Settings.ACTION_SETTINGS);
                            startActivity(intent);
                        }
                    });
                    setting.setNegativeButton("忽略", null);
                    AlertDialog dialog = setting.create();
                    dialog.getWindow().setType((WindowManager.LayoutParams.TYPE_SYSTEM_ALERT));
                    dialog.show();
                    break;
                default:

            }

        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        start = (ImageButton)findViewById(R.id.start);
        stop = (ImageButton)findViewById(R.id.stop);
        help = (ImageButton)findViewById(R.id.help);
        mobileTrafficData = (RadioButton)findViewById(R.id.mobiletrafficdata);
        allTrafficData = (RadioButton)findViewById(R.id.alltrafficdata);
        trafficDataOption = (RadioGroup)findViewById(R.id.trafficdataoption);
        limitedData = (EditText)findViewById(R.id.limiteddata);
        showData = (TextView)findViewById(R.id.showdata);
        mainPanle = (LinearLayout)findViewById(R.id.mainpanel);
        mainPanle.setBackgroundResource(R.drawable.bg);
        showData.setText("0MB");
        help.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                scaleAnimate(help);
                AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);
                dialog.setTitle("帮助信息");
                dialog.setMessage("1.应用主要是提醒您节制使用流量;\n2.所有数据指wifi和手机卡流量,移动数据指手机卡流量;\n" +
                        "3.主要的操作方法是选择监控的流量,然后填入你想监控值,然后点击开始就可以了;\n4.比如,我手机流量快没有了,我选择移动流量,然后" +
                        "填入5,然后点击开始,然后让应用后台,你就玩玩游戏,看看网页,当流量超过了5M,就会弹出信息,告诉你,你已经用到这么多了,需要关闭网络了.");
                dialog.show();
            }
        });
        start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                scaleAnimate(start);
                trafficLimitedData = limitedData.getText().toString();
                if(trafficLimitedData.equals("")){
                    Toast.makeText(getApplicationContext(),"请填入监控值",Toast.LENGTH_SHORT).show();
                }
                else{
                    if(serviceFlag){
                        Toast.makeText(getApplicationContext(),"监控已经开启",Toast.LENGTH_SHORT).show();
                    }
                    else{
                        Intent intent = new Intent(MainActivity.this,TrafficHandle.class);
                        intent.putExtra("trafficLimitedData",trafficLimitedData);
                        intent.putExtra("trafficDataOption",option);
                        serviceFlag = MainActivity.this.bindService(intent,monitor,BIND_AUTO_CREATE);
                        if(serviceFlag){
                            Toast.makeText(getApplicationContext(),"开始对网络数据进行监控",Toast.LENGTH_SHORT).show();
                            displayDataThread = new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    Looper.prepare();
                                    while(true){
                                        Message displayMsg = new Message();
                                        displayMsg.what = DISPLAYTRAFFICDATA;
                                        displayTrafficData.sendMessage(displayMsg);
                                        SystemClock.sleep(1000);
                                        if(trafficBinder!=null){
                                            if (trafficBinder.getTrafficData() > Float.parseFloat(trafficLimitedData)) {
                                                if(!hasDialog){
                                                    hasDialog = true;
                                                    displayMsg = new Message();
                                                    displayMsg.what = DISPLAYDIALOG;
                                                    displayTrafficData.sendMessage(displayMsg);
                                                }
                                            }
                                        }
                                    }
                                }
                            });
                            displayDataThread.start();
                            limitedData.setEnabled(false);
                            start.setEnabled(false);
                            allTrafficData.setEnabled(false);
                            mobileTrafficData.setEnabled(false);
                        }
                        else{
                            Toast.makeText(getApplicationContext(),"监控开启失败",Toast.LENGTH_SHORT).show();
                        }
                    }
                }
            }
        });
        stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(serviceFlag){
                    scaleAnimate(stop);
                    serviceFlag = false;
                    MainActivity.this.unbindService(monitor);
                    displayDataThread.interrupt();
                    trafficBinder = null;
                    showData.setText("0MB");
                    Toast.makeText(getApplicationContext(),"停止对网络数据进行监控",Toast.LENGTH_SHORT).show();
                    limitedData.setEnabled(true);
                    start.setEnabled(true);
                    allTrafficData.setEnabled(true);
                    mobileTrafficData.setEnabled(true);
                }
                else{
                    Toast.makeText(getApplicationContext(),"监控未曾开启",Toast.LENGTH_SHORT).show();
                }
            }
        });

        trafficDataOption.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if(checkedId == mobileTrafficData.getId()){
                    Toast.makeText(getApplicationContext(),"您选择了监控移动数据", Toast.LENGTH_SHORT).show();
                    option = 0;
                }
                if(checkedId == allTrafficData.getId()){
                    Toast.makeText(getApplicationContext(),"您选择了监控所有数据", Toast.LENGTH_SHORT).show();
                    option = 1;
                }
            }
        });

    }

    public void scaleAnimate(View object){
        ScaleAnimation animation = new ScaleAnimation(0.1f,1.0f,0.1f,1.0f, RotateAnimation.RELATIVE_TO_SELF,0.5f,RotateAnimation.RELATIVE_TO_SELF,0.5f);
        animation.setDuration(500);
        object.startAnimation(animation);
    }
}


